package com.heihei.itextdemo.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heihei.itextdemo.dto.CommonResponseDTO;
import com.heihei.itextdemo.entity.HumanEntity;
import com.heihei.itextdemo.service.HumanService;
import com.heihei.itextdemo.service.TestService;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

@Service
public class TestServiceImpl implements TestService {
    @Resource
    private HumanService humanService;
    /**
     * 添加本地图片path
     * @param gender 1男 2女
     */
    @Override
    public CommonResponseDTO<String> addLocalImgPath(Integer gender) throws FileNotFoundException {
        if(gender == null) {
            return CommonResponseDTO.forFail("性别不能为空");
        }
        //本地图片存放位置
        File imgDir = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "itext-imgs");
        if(gender == 1) {
            //添加男性本地图片path
            List<HumanEntity> list = humanService.list(Wrappers.<HumanEntity>query().lambda().eq(HumanEntity::getGender, 1));
            //男 图片存放位置
            File boyDir = new File(imgDir, "boy");
            File[] boyImgList = boyDir.listFiles();
            int i = 0;
            for (HumanEntity humanEntity : list) {
                if(i >= boyImgList.length) i = 0;
                humanEntity.setLocalImgPath("/boy/" + boyImgList[i++].getName());
            }
            humanService.updateBatchById(list);
            return CommonResponseDTO.forSuccess();
        }
        if(gender == 2) {
            //添加女性本地图片path
            List<HumanEntity> list = humanService.list(Wrappers.<HumanEntity>query().lambda().eq(HumanEntity::getGender, 2));
            //男 图片存放位置
            File boyDir = new File(imgDir, "girl");
            File[] boyImgList = boyDir.listFiles();
            int i = 0;
            for (HumanEntity humanEntity : list) {
                if(i >= boyImgList.length) i = 0;
                humanEntity.setLocalImgPath("/girl/" + boyImgList[i++].getName());
            }
            humanService.updateBatchById(list);
            return CommonResponseDTO.forSuccess();
        }
        return CommonResponseDTO.forFail("参数非法");
    }
}
